"use strict";

const fs = require("fs");
const os = require("os");
const path = require("path");
const { app: eApp } = require("electron");
const { isDev } = require("ee-core/ps");

const defaultConfig = {
  eap5Host: "http://e52.hieap.cn",
  ssoHost: "https://sso.fdauto.com",
  eap1Host: "http://eap.fdauto.com",
  eap2Host: "http://eap2.fdauto.com",
  mailHost: "http://fdmail.fdauto.com:8003",
};

class ConfigService {
  curConfig = {};
  constructor() {
    // 设置存储文件路径
    let filePath = "";
    if (isDev()) {
      filePath = path.join(process.cwd(), "data", "config.json");
    } else {
      const exePath = eApp.getPath("exe");
      let exeDir = path.dirname(exePath);
      // mac电脑特殊处理
      if (os.platform() === "darwin") {
        // 检查是否从DMG运行
        const isFromDMG = exeDir.includes("/Volumes/");

        if (isFromDMG) {
          // 从DMG运行，使用用户目录
          exeDir = eApp.getPath("userData");
        }
      }

      filePath = path.join(exeDir, "data", "config.json");
    }
    this.filePath = filePath;
    console.log("配置文件路径:", this.filePath);
    this.init();
  }
  init() {
    try {
      // 获取配置文件所在目录路径
      const dir = path.dirname(this.filePath);

      // 如果目录不存在，则递归创建
      if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
      }

      // 如果配置文件不存在，写入默认配置
      if (!fs.existsSync(this.filePath)) {
        fs.writeFileSync(this.filePath, JSON.stringify(defaultConfig, null, 2));
        this.curConfig = defaultConfig;
      } else {
        const data = fs.readFileSync(this.filePath, "utf8");
        const config = JSON.parse(data);
        this.curConfig = Object.assign({}, defaultConfig, config);
        fs.writeFileSync(
          this.filePath,
          JSON.stringify(this.curConfig, null, 2)
        );
      }
    } catch (error) {
      console.error("初始化配置文件失败:", error);
      throw error;
    }
  }
  get(key) {
    try {
      // const data = fs.readFileSync(this.filePath, "utf8");
      // const config = JSON.parse(data);

      if (key) {
        return key in this.curConfig ? this.curConfig[key] : null;
      }

      return this.curConfig;
    } catch (error) {
      console.error("读取配置失败:", error);
      return key ? null : null;
    }
  }

  set(key, value) {
    try {
      const data = fs.readFileSync(this.filePath, "utf8");
      const currentConfig = JSON.parse(data);

      const newConfig =
        key && typeof key === "object"
          ? { ...currentConfig, ...key }
          : { ...currentConfig, [key]: value };

      fs.writeFileSync(this.filePath, JSON.stringify(newConfig, null, 2));
      return true;
    } catch (error) {
      console.error("写入配置失败:", error);
      return false;
    }
  }
}

module.exports = {
  ConfigService,
  configService: new ConfigService(),
};
